from pymongo import MongoClient
from urllib.parse import quote_plus
from flask import current_app

from lina.settings import config

global_connection = None


def db():
    global global_connection

    config_item = config[current_app.env]
    db_name = config_item.db_name

    while global_connection == None:
        try:
            if not global_connection is None:
                global_connection.close()

            user = config_item.user
            password = config_item.password
            host = config_item.host
            port = config_item.port

            url = "mongodb://%s:%s@%s:%s" % (quote_plus(user),
                                             quote_plus(password), host, port)

            global_connection = MongoClient(url)
            current_app.logger.warn(global_connection)

        except Exception as e:
            global_connection = None
            current_app.logger.error('连接mongodb数据库时发生错误')

    return global_connection[db_name]


def truncate(col):
    col = db()[col]
    col.remove()


def insert_batch(mongo_col, list_to_add):
    col = db()[mongo_col]
    result = col.insert_many(list_to_add)
    return result


def insert(mongo_col, data_to_add):
    col = db()[mongo_col]
    result = col.insert(data_to_add)
    return result


def query(mongo_col):
    col = db()[mongo_col]
    results = []
    for item in col.find():
        results.append(item)
    return results
